package com.monlyu.bean;

import com.monlyu.config.AppArgs;
import com.monlyu.util.StringUtil;
import com.monlyu.util.WebOptUtil;

/**
 * 这个是有关数据库的字段备注
 */
public class CommentBean {

	private String table;

	private String field;

	private String comment;

	public String getTable() {
		return table;
	}

	public void setTable(String table) {
		this.table = table;
	}

	public String getField() {
		return field;
	}

	public void setField(String field) {
		this.field = field;
	}

	public String getComment() {
		return comment;
	}

	public void setComment(String comment) {
		this.comment = comment;
	}

	private String toMysql() {
		StringBuilder builder = new StringBuilder();
		if (isHead()) {
			builder.append("ALTER TABLE ");
			builder.append(db());
			builder.append(".");
			builder.append(getTable());
			builder.append(" COMMENT = '");
			builder.append(StringUtil.shot(getComment(), 60));
			builder.append("'");
		} else {
			builder.append("show create table ");
			builder.append(db());
			builder.append(".");
			builder.append(getTable());
		}
		return builder.toString();
	}

	public boolean isHead() {
		return StringUtil.isEmpty(getField());
	}

	private String toOracle() {
		StringBuilder builder = new StringBuilder("COMMENT ON ");
		if (isHead()) {
			builder.append("TABLE ");
			builder.append(getTable());
		} else {
			builder.append("COLUMN ");
			builder.append(getTable() + "." + getField());
		}
		builder.append(" IS '");
		builder.append(getComment());
		builder.append("'");
		return builder.toString();
	}

	private String toSQLServer() {
		return "";
	}

	@Override
	public String toString() {
		final String database = WebOptUtil.APP_ARGS.getDataBase().getName();
		if (database.equals(AppArgs.DB_SQLSERVER)) {
			return toSQLServer();
		} else if (database.equals(AppArgs.DB_ORACLE)) {
			return toOracle();
		} else {
			return toMysql();
		}
	}

	/** 获取数据库的名称 */
	private String db() {
		return WebOptUtil.APP_ARGS.getDataBase().getDbName();
	}

	public boolean isMysql() {
		return WebOptUtil.APP_ARGS.getDataBase().getName().equals(AppArgs.DB_MYSQL);
	}

	/** 组装修改mysql字段说明的字符串 */
	public static String mysqlComent(String ddlstat, CommentBean bean) {
		String[] columns = ddlstat.substring(ddlstat.indexOf("(") + 1, ddlstat.lastIndexOf(")")).split("\n");
		for (String column : columns) {
			if (column.trim().startsWith(bean.getField(), 1)) {
				StringBuilder builder = new StringBuilder("ALTER TABLE ");
				builder.append(bean.db());
				builder.append(".");
				builder.append(bean.getTable());
				builder.append(" MODIFY COLUMN ");
				builder.append((column.substring(0, column.length() - 1)).trim());
				builder.append(" COMMENT '");
				builder.append(bean.getComment());
				builder.append("'");
				return builder.toString();
			}
		}
		return null;
	}
}
